/**
 * 
 */
package com.ycnet.springapp.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author ycnet
 *
 */
@Configuration
@EnableWebSecurity
// @EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private DataSource dataSource;

	@Autowired
	private CustomUserDetailsService customUserDetailsService;

	@Override
	protected void configure(AuthenticationManagerBuilder registry) throws Exception {
		/*
		 * registry .inMemoryAuthentication() .withUser("ycnet") // #1
		 * .password("ycnet") .roles("USER") .and() .withUser("admin") // #2
		 * .password("admin") .roles("ADMIN","USER");
		 */

		registry.userDetailsService(customUserDetailsService);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/app/resources/**").antMatchers("/resources/**"); //
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable().authorizeRequests()//
				.antMatchers("/app/login", "/app/login/form**", "/app/register", "/app/logout").permitAll()//
				.antMatchers("/app/admin", "/app/admin/**").hasRole("ADMIN") //
				.anyRequest().authenticated().and().formLogin() //
				.loginPage("/app/login/form") //
				.loginProcessingUrl("/app/login").failureUrl("/app/login/form?error").permitAll() //
				.and().logout().logoutUrl("/app/logout");
	}
}
